package com.shxzz.easy12306.framework.starter.user.toolkit;

import com.alibaba.fastjson2.JSON;
import com.shxzz.easy12306.framework.starter.user.core.UserInfoDTO;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;

import java.util.Date;

/**
 * JWT工具类
 *
 * @author shxzz
 * @create 2024-02-24-18:51
 */
@Slf4j
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public final class JWTUtil {
    private static final long EXPIRATION = 86400L;
    public static final String TOKEN_PREFIX = "Bearer ";
    private static final String SECRET = "EASY12306dansidnwsjdhjsafhg156184fsda5";
    private static final String ISSUER = "easy12306";


    public static String generateAccessToken(UserInfoDTO userInfo) {
        String jwt = Jwts.builder()
                .signWith(SignatureAlgorithm.HS512, SECRET)
                .setIssuer(ISSUER)
                .setIssuedAt(new Date())
                .setSubject(JSON.toJSONString(userInfo))
                .setExpiration(new Date(System.currentTimeMillis() + EXPIRATION * 1000))
                .compact();
        return TOKEN_PREFIX + jwt;
    }

    public static UserInfoDTO parseAccessToken(String token) {
        if(!StringUtils.hasLength(token)) return null;

        String jwt = token.replace(TOKEN_PREFIX, "");
        try {
            String subject = Jwts.parser()
                    .setSigningKey(SECRET)
                    .parseClaimsJws(jwt)
                    .getBody()
                    .getSubject();
            return JSON.parseObject(subject, UserInfoDTO.class);
        } catch (ExpiredJwtException e) {

        } catch (Exception e) {
            log.error("JWT token 解析失败", e);
        }
        return null;
    }

}
